package com.meida.module.arc.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.query.CriteriaDelete;
import com.meida.common.utils.ApiAssert;
import com.meida.module.arc.client.constants.ArchiveConstants;
import com.meida.module.arc.client.entity.ArcDb;
import com.meida.module.arc.client.entity.ArcDbRecord;
import com.meida.module.arc.client.utils.ArcUtils;
import com.meida.module.arc.provider.mapper.ArcDbRecordMapper;
import com.meida.module.arc.provider.service.ArcDbRecordService;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.module.arc.provider.service.ArcDbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.query.CriteriaQuery;
import org.springframework.transaction.annotation.Propagation;
import com.meida.common.mybatis.query.CriteriaSave;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 备份记录接口实现类
 *
 * @author flyme
 * @date 2021-12-25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ArcDbRecordServiceImpl extends BaseServiceImpl<ArcDbRecordMapper, ArcDbRecord> implements ArcDbRecordService {

    @Autowired
    private ArcDbService arcDbService;
    @Override
    public ResultBody beforeAdd(CriteriaSave cs, ArcDbRecord adr, EntityMap extra) {
        return ResultBody.ok();
    }



    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<ArcDbRecord> cq, ArcDbRecord adr, EntityMap requestMap) {
      cq.orderByDesc("adr.createTime");
      return ResultBody.ok();
    }

    @Override
    public ResultBody beforeDelete(CriteriaDelete<ArcDbRecord> cd) {
        ApiAssert.isNotEmpty("要删除的备份记录为空",cd.getIdValue());
        return ResultBody.ok();
    }

    @Override
    public ResultBody back(Map var1) {
        Object dbRecordId = var1.get("dbRecordId");
        ApiAssert.isNotEmpty("要还原的备份记录不能为空",dbRecordId);
        ArcDbRecord record = this.getById(Long.parseLong(dbRecordId.toString()));
        ApiAssert.isNotEmpty("要还原的备份记录不能为空",record);
        //TODO 基于备份记录进行还原
        return ResultBody.ok();
    }

    @Override
    public String getDefaultRecordPath(){
        String rootPath = ArcUtils.getRootTempPath();
        return rootPath+ ArchiveConstants.DEFAULT_DB_RECORD_PATH;
    }

     //TODO 自动备份任务调用该方法,如果是saas环境需要处理租户id
    //TODO 自动备份必传参数  fileName:文件名(必须以.sql结尾)  type:2(必须为2)
    @Override
    public ResultBody doDbRecord(Map var1) {
        Object fileName = var1.get("fileName");
        Object type = var1.get("type");
        ApiAssert.isNotEmpty("备份名称不能为空",fileName);
        String fileNameStr = fileName.toString();
        if(fileNameStr.length()<4||fileNameStr.indexOf(".sql")<(fileNameStr.length()-4)){
            return ResultBody.failed("备份文件名称必须以.sql结尾");
        }
        CriteriaQuery<ArcDbRecord> query = new CriteriaQuery<ArcDbRecord>(ArcDbRecord.class);
        query.lambda().eq(ArcDbRecord::getFileName,fileNameStr);
        Long count = this.count(query);
        if(count>0){
            ApiAssert.failure("备份文件名称重复");
        }
        ArcDbRecord record = new ArcDbRecord();
        record.setFileName(fileNameStr);
        record.setType(FlymeUtils.isEmpty(type)?2:1);


        //获取系统默认备份路径
        QueryWrapper<ArcDb> dbQuery = new QueryWrapper<>();
        dbQuery.orderByDesc("createTime");
        List<ArcDb> list = this.arcDbService.list(dbQuery);
        String recordPath = "";
        if(FlymeUtils.isNotEmpty(list)){
            ArcDb db = list.get(0);
            if(FlymeUtils.isEmpty(db.getPath())){
                recordPath = getDefaultRecordPath();
            }else{
                recordPath = db.getPath();
            }
        }else{
            recordPath = getDefaultRecordPath();
        }
        record.setFilePath(recordPath);
        this.save(record);
        //TODO 执行数据库备份程序
        return ResultBody.ok();
    }

}
